package nbcp.myoql.db.sql.extend

import com.zaxxer.hikari.HikariDataSource
import nbcp.base.extend.HasValue
import nbcp.base.extend.Slice
import nbcp.myoql.db.enums.SqlDatabaseEnum
import javax.sql.DataSource

fun DataSource.getDbType(): SqlDatabaseEnum? {
    if (!(this is HikariDataSource)) {
        throw RuntimeException("必须是 HikariDataSource 类型！");
    }
    var ret: SqlDatabaseEnum? = null
    if (this.driverClassName.HasValue) {

        ret = SqlDatabaseEnum.values()
            .firstOrNull {
                this.driverClassName.contains(
                    it.toString().lowercase().replace("_", "")
                )
            }

        if (ret != null) {
            return ret;
        }
    }

    if (this.jdbcUrl.HasValue) {
        var url = this.jdbcUrl.Slice("jdbc:".length)

        ret = SqlDatabaseEnum.values()
            .firstOrNull { url.startsWith(it.toString().lowercase().replace("_", "")) }

        if (ret != null) {
            return ret;
        }
    }

    return ret;
}